<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>序列化舞台并将JSON字符串</title>
  <script src="/konva.min.js"></script>
</head>

<body>
  <div id="container" style="border:1px solid black; width: 800px; height: 600px;"></div>
  <button id="serialize">序列化</button>
  <button id="deserialize">反序列化</button>
  <textarea id="jsonOutput" style="width: 100%; height: 100px;"></textarea>

  <script>
    // Create a stage
    var stage = new Konva.Stage({
      container: 'container',
      width: 800,
      height: 600
    })

    // Create a layer
    var layer = new Konva.Layer()
    stage.add(layer)

    // Add a rectangle to the layer
    var rect = new Konva.Rect({
      x: 50,
      y: 50,
      width: 100,
      height: 100,
      fill: 'red',
      stroke: 'black',
      strokeWidth: 2,
      draggable: true
    })

    layer.add(rect)
    layer.draw()

    // Serialize button event listener
    document.getElementById('serialize').addEventListener('click', function () {
      var json = stage.toJSON()
      document.getElementById('jsonOutput').value = json
    })

    // Deserialize button event listener
    document.getElementById('deserialize').addEventListener('click', function () {
      var json = document.getElementById('jsonOutput').value
      // Clear the stage
      stage.destroyChildren()
      // Create a new stage from the JSON string
      stage = Konva.Node.create(json, 'container')
    });
  </script>
</body>

</html>